<template>
  <div class="location-selector">
    <div class="selector-content">
      <div class="location-search">
        <div class="search-header">
          <a-input-search 
            v-model="searchQuery" 
            placeholder="搜索库位" 
            allow-clear
            @search="handleSearch"
          />
          <a-button type="outline" @click="refreshLocations">
            <template #icon><icon-refresh /></template>
            刷新库位
          </a-button>
        </div>
      </div>
      
      <a-spin :loading="loading">
        <div class="location-container">
          <div class="location-filters">
            <a-space>
              <a-select 
                v-if="props.operationType !== 'pick'" 
                v-model="filterZone" 
                placeholder="区域筛选" 
                allow-clear
                style="width: 120px"
              >
                <a-option v-for="zone in zones" :key="zone.id" :value="zone.id">
                  {{ zone.name }}
                </a-option>
              </a-select>
              
              <a-select 
                v-model="filterStatus" 
                placeholder="状态筛选" 
                allow-clear
                style="width: 120px"
              >
                <a-option value="AVAILABLE">可用</a-option>
                <a-option value="FULL">已满</a-option>
                <a-option value="LOCKED">已锁定</a-option>
              </a-select>
            </a-space>
          </div>
          
          <a-tabs type="card">
            <a-tab-pane key="grid" title="网格视图">
              <div class="location-grid">
                <div 
                  v-for="location in filteredLocations"
                  :key="location.id"
                  class="location-cell"
                  :class="{
                    'available': location.status === 1,
                    'locked': location.status === 0,
                    'selected': selectedLocation?.id === location.id
                  }"
                  @click="selectLocation(location)"
                >
                  <div class="location-code">{{ location.code }}</div>
                  <div class="location-info">
                    <div class="location-stock-info">
                      <!-- 根据操作类型显示不同信息 -->
                      <span v-if="props.operationType === 'pick'">可用: {{ location.current_quantity || 0 }}</span>
                      <span v-else>库存: {{ location.current_quantity || 0 }} / {{ location.capacity || 0 }}</span>
                    </div>
                    <!-- 库位使用率条 (仅在上架且有容量时显示) -->
                    <div class="location-usage" v-if="props.operationType !== 'pick' && (location.capacity || 0) > 0">
                      <div 
                        class="usage-bar" 
                        :style="{ width: `${location.usagePercentage || 0}%` }" 
                      ></div>
                    </div>
                  </div>
                </div>
                <p v-if="filteredLocations.length === 0 && !loading">没有找到合适的库位。</p>
              </div>
            </a-tab-pane>
            
            <a-tab-pane key="list" title="列表视图">
              <a-table
                :data="filteredLocations"
                :pagination="{ pageSize: 10 }"
                :bordered="false"
                size="small"
                :row-class="getRowClass"
                @row-click="(record) => selectLocation(record)"
                style="width: 100%"
              >
                <template #columns>
                  <a-table-column title="库位编码" data-index="code" align="center" />
                  <a-table-column title="库存 / 容量" align="center">
                    <template #cell="{ record }">
                      {{ record.current_quantity || 0 }} / {{ record.capacity || 0 }}
                    </template>
                  </a-table-column>
                  <a-table-column title="状态" data-index="status" align="center">
                    <template #cell="{ record }">
                      <a-tag :color="record.status === 1 ? 'green' : 'red'">
                        {{ record.status === 1 ? '可用' : '禁用' }}
                      </a-tag>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
              <p v-if="filteredLocations.length === 0 && !loading" style="text-align: center; margin-top: 16px;">没有找到合适的库位。</p>
            </a-tab-pane>
          </a-tabs>
        </div>
        
        <div class="location-selected" v-if="selectedLocation">
          <a-divider>已选库位信息</a-divider>
          <a-descriptions :column="{ xs: 1, sm: 2 }" layout="inline-horizontal" size="small" bordered>
            <a-descriptions-item label="库位编码">{{ selectedLocation.code }}</a-descriptions-item>
            <a-descriptions-item label="当前状态">
              <a-tag :color="selectedLocation.status === 1 ? 'green' : 'red'">
                {{ selectedLocation.status === 1 ? '可用' : '禁用' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="所属仓库">{{ props.warehouseName || 'N/A' }}</a-descriptions-item>
            <a-descriptions-item label="当前数量">{{ selectedLocation.current_quantity || 0 }}</a-descriptions-item>
            <a-descriptions-item v-if="props.operationType !== 'pick'" label="最大容量">{{ selectedLocation.capacity || 0 }}</a-descriptions-item>
            <a-descriptions-item v-if="props.operationType !== 'pick'" label="可用数量">{{ selectedLocation.availableCapacity ?? 0 }}</a-descriptions-item>
          </a-descriptions>
          
          <div class="location-action">
            <a-space>
              <a-button 
                type="primary" 
                @click="confirmLocation"
                :disabled="!canConfirm"
              >
                确认选择
              </a-button>
              <a-button @click="clearSelection">
                清除选择
              </a-button>
            </a-space>
          </div>
        </div>
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import { useInventoryStore } from '@/stores/inventory';
import { useWarehouseStore } from '@/stores/warehouse';
import { IconRefresh } from '@arco-design/web-vue/es/icon';
import axios from 'axios';

const props = defineProps({
  productId: {
    type: [Number, String],
    required: true
  },
  warehouseId: {
    type: [Number, String],
    default: null
  },
  warehouseName: {
    type: String,
    default: ''
  },
  excludedLocations: {
    type: Array,
    default: () => []
  },
  operationType: {
    type: String,
    default: 'pick', // 'pick' 或 'putaway'
    validator: (value) => ['pick', 'putaway'].includes(value)
  },
  requiredQuantity: {
    type: Number,
    default: 0
  },
  allowQuantityInput: {
    type: Boolean,
    default: true
  },
  modelValue: {
    type: [Number, String, null],
    default: null
  },
  loadAll: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择库位'
  },
  onlyAvailable: {
    type: Boolean,
    default: false
  },
  filterFn: {
    type: Function,
    default: null
  }
});

const emit = defineEmits(['select', 'update:quantity', 'update:modelValue', 'change']);

const inventoryStore = useInventoryStore();
const warehouseStore = useWarehouseStore();
const loading = ref(false);
const locations = ref([]);
const selectedLocation = ref(props.modelValue);
const searchQuery = ref('');
const filterZone = ref(null);
const filterStatus = ref(null);
const quantity = ref(0);
const locationOptions = ref([]);

// 动态计算可用区域列表
const zones = computed(() => {
  if (!locations.value || locations.value.length === 0) {
    return [];
  }
  const uniqueZones = new Map();
  locations.value.forEach(loc => {
    // 假设库位对象中有 area 字段
    if (loc.area && !uniqueZones.has(loc.area)) {
      uniqueZones.set(loc.area, { id: loc.area, name: loc.area }); // 使用 area 作为 id 和 name
    }
  });
  return Array.from(uniqueZones.values()).sort((a, b) => a.name.localeCompare(b.name)); // 按名称排序
});

// 是否可以确认选择
const canConfirm = computed(() => {
  // Only check if a location is selected
  return !!selectedLocation.value;
});

// 刷新库位数据 - 公开给父组件使用
const refreshLocations = async () => {
  console.log('[LocationSelector] 强制刷新库位数据');
  Message.info('正在刷新库位数据...');
  await fetchLocations(true); // 传入true表示强制刷新
  Message.success('库位数据已更新');
};

// 获取库位列表 - 根据操作类型调用不同方法
const fetchLocations = async (forceRefresh = false) => {
  loading.value = true;
  
  try {
    console.log(`[LocationSelector] 正在获取库位数据，商品ID: ${props.productId}, 仓库ID: ${props.warehouseId}, 强制刷新: ${forceRefresh}`);
    
    // 获取商品所有库位信息
    if (props.operationType === 'pick') {
      // 拣货模式 - 获取商品在指定仓库的库位
      const options = {
        warehouseId: props.warehouseId,
        forceRefresh: forceRefresh
      };
      
      if (props.loadAll) {
        options.loadAll = true; // 加载所有库位，包括无库存的
      }
      
      const productLocations = await inventoryStore.getProductLocations(props.productId, options);
      console.log(`[LocationSelector] 拣货模式库位数据:`, productLocations);
      
      // 处理库位数据
      locations.value = productLocations.map(loc => {
        // 计算可用数量
        const availableQty = Number(loc.quantity || 0) - Number(loc.lock_stock || 0);
        
        // 提取库位数据，兼容新旧数据结构
        const locationData = loc.location || {};
        const locationId = loc.location_id || locationData.id;
        const locationCode = locationData.code || loc.location_code || '未知编码';
        
        return {
          id: locationId,
          code: locationCode,
          name: locationData.name || locationCode, // 如果没有name就用code
          warehouse_id: loc.warehouse_id || props.warehouseId,
          current_quantity: availableQty, // 当前可用数量
          capacity: locationData.capacity || 0,
          status: locationData.status || 1, // 假设1为可用
          area: locationData.area || '',
          remark: locationData.remark || '',
          usagePercentage: locationData.capacity ? 
            (availableQty / locationData.capacity * 100).toFixed(0) : 0
        }
      });
      
      // 过滤出有库存的库位(确保库位可用且有足够库存)
      if (props.onlyAvailable) {
        locations.value = locations.value.filter(loc => 
          loc.status === 1 && loc.current_quantity > 0
        );
      }

      console.log('[LocationSelector] 处理后的库位列表:', locations.value);
    } else {
      // 上架模式 - 获取仓库的所有可用库位
      const warehouseLocations = await warehouseStore.getWarehouseLocations(props.warehouseId);
      
      // 映射库位数据为组件需要的格式
      locations.value = warehouseLocations.map(loc => {
        // 计算使用率
        const usage = loc.current_quantity && loc.capacity ? 
          (loc.current_quantity / loc.capacity * 100).toFixed(0) : 0;
        
        return {
          id: loc.id,
          code: loc.code || '未知编码',
          name: loc.name || loc.code,
          warehouse_id: loc.warehouse_id,
          current_quantity: loc.current_quantity || 0,
          capacity: loc.capacity || 0,
          status: loc.status,
          area: loc.area || '',
          remark: loc.remark || '',
          availableCapacity: (loc.capacity || 0) - (loc.current_quantity || 0),
          usagePercentage: usage
        };
      });
    }
    
    // 过滤掉被排除的库位
    if (props.excludedLocations?.length > 0) {
      locations.value = locations.value.filter(loc => !props.excludedLocations.includes(loc.id));
    }
    
    // 应用自定义过滤函数
    if (typeof props.filterFn === 'function') {
      locations.value = locations.value.filter(props.filterFn);
    }
    
    // 尝试选择第一个库位
    if (locations.value.length > 0 && !selectedLocation.value) {
      selectLocation(locations.value[0]);
    }
    
  } catch (error) {
    console.error('[LocationSelector] 获取库位数据失败:', error);
    Message.error(`获取库位数据失败: ${error.message || '未知错误'}`);
    locations.value = [];
  } finally {
    loading.value = false;
  }
};

// 确定是否为推荐库位
const determineIfRecommended = (location) => {
  if (props.operationType === 'pick') {
    // 拣货推荐: 库存足够且不是混合存储
    return location.availableCapacity >= props.requiredQuantity && 
           !location.isMixed;
  } else {
    // 上架推荐: 空库位或者已有同种商品且空间足够
    return (location.current_quantity === 0) || 
           (location.productId === props.productId && 
            (location.maxQuantity - location.current_quantity) >= props.requiredQuantity);
  }
};

// 获取可用数量
const getAvailableQuantity = (location) => {
  if (props.operationType === 'pick') {
    // 拣货可用量就是当前库存
    return location.current_quantity || 0;
  } else {
    // 上架可用量是剩余空间
    return location.maxQuantity - location.current_quantity;
  }
};

// 获取最大可操作数量
const getMaxQuantity = () => {
  if (!selectedLocation.value) return 0;
  
  if (props.operationType === 'pick') {
    // 拣货最大数量 = 当前库存 vs 需求数量
    return Math.min(selectedLocation.value.current_quantity || 0, props.requiredQuantity || Infinity);
  } else { // putaway
    // 上架最大数量 = 可用容量 vs 需求数量
    const availableCapacity = selectedLocation.value.availableCapacity ?? 0;
    return Math.min(availableCapacity, props.requiredQuantity || Infinity);
  }
};

// 筛选库位
const filteredLocations = computed(() => {
  let result = locations.value;
  
  // 排除已选择的库位
  const excludedIds = props.excludedLocations.map(loc => loc.id);
  result = result.filter(loc => !excludedIds.includes(loc.id));
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(loc => 
      (loc.code && loc.code.toLowerCase().includes(query)) || 
      (loc.area && loc.area.toLowerCase().includes(query))
    );
  }
  
  // 区域筛选
  if (filterZone.value) {
    result = result.filter(loc => loc.area === filterZone.value);
  }
  
  // 状态筛选
  if (filterStatus.value !== null && filterStatus.value !== undefined) { 
    result = result.filter(loc => loc.status === filterStatus.value);
  }
  
  return result;
});

// 获取表格行类名
const getRowClass = (record) => {
  if (selectedLocation.value && record.id === selectedLocation.value.id) {
    return 'location-row-selected';
  }
  return '';
};

// 使用率颜色
const getUsageColor = (record) => {
  const percent = record.usagePercentage;
  if (percent > 90) return '#f5222d';
  if (percent > 70) return '#fa8c16';
  if (percent > 50) return '#faad14';
  return '#52c41a';
};

// 选择库位
const selectLocation = (location) => {
  if (!location) return;
  
  // 不允许选择禁用状态的库位用于上架
  if (props.operationType === 'putaway' && location.status !== 1) {
    Message.warning('目标库位不可用，请选择其他库位');
    return;
  }
  
  selectedLocation.value = location;
  // Reset quantity if needed, though input is removed
  quantity.value = 0; 
};

// 确认选择
const confirmLocation = () => {
  if (!selectedLocation.value) { 
     Message.warning('请先选择一个有效的库位');
     return;
  }
  
  // 计算默认数量 - 对于上架操作，设置为需求数量和可用容量的较小值
  let defaultQuantity = 0;
  if (props.operationType === 'putaway') {
    const availableCapacity = selectedLocation.value.availableCapacity || 0;
    defaultQuantity = Math.min(props.requiredQuantity || 0, availableCapacity);
  } else { // 拣货操作
    // 默认设置为出库需求数量，但不能超过库位当前库存量
    defaultQuantity = Math.min(props.requiredQuantity || 0, selectedLocation.value.current_quantity || 0);
  }
  
  // 数量必须大于0
  if (defaultQuantity <= 0) {
    defaultQuantity = props.requiredQuantity > 0 ? props.requiredQuantity : 1;
  }
  
  console.log(`确认选择库位: ${selectedLocation.value.code}, 数量: ${defaultQuantity}`);
   
  emit('select', {
    location: selectedLocation.value,
    quantity: defaultQuantity // 返回计算出的默认数量
  });
};

// 清除选择
const clearSelection = () => {
  selectedLocation.value = null;
  quantity.value = 0;
};

// 搜索处理
const handleSearch = () => {
  // 搜索过滤由计算属性自动完成
};

// 监听数量变化
watch(quantity, (newValue) => {
  emit('update:quantity', newValue);
});

// 监听输入值变化
watch(() => props.modelValue, (newVal) => {
  selectedLocation.value = newVal;
});

// 过滤库位选项
const filterOption = (inputValue, option) => {
  if (!inputValue) return true;
  const lowerCaseInput = inputValue.toLowerCase();
  
  // 在编码、名称和区域中搜索
  return option.code?.toLowerCase().includes(lowerCaseInput) ||
    option.label?.toLowerCase().includes(lowerCaseInput) ||
    option.area?.toLowerCase().includes(lowerCaseInput) ||
    option.shelf?.toLowerCase().includes(lowerCaseInput) ||
    option.level?.toLowerCase().includes(lowerCaseInput);
};

// 处理选择变化
const handleChange = (value) => {
  emit('update:modelValue', value);
  
  // 找到选中的库位对象
  const selectedOption = locationOptions.value.find(item => item.value === value);
  emit('change', selectedOption);
  
  console.log('库位选择器: 选择已变更', value, selectedOption);
};

// 加载库位数据
const loadLocations = async () => {
  if (loading.value) return;
  
  loading.value = true;
  console.log('库位选择器: 开始加载库位数据', {
    warehouseId: props.warehouseId,
    onlyAvailable: props.onlyAvailable
  });
  
  try {
    // 构建请求参数
    const params = {
      page: 1,
      pageSize: 999 // 获取全部库位
    };
    
    // 如果指定了仓库ID，加入过滤条件
    if (props.warehouseId) {
      params.warehouseId = props.warehouseId;
    }
    
    // 如果只显示可用的库位，加入状态过滤
    if (props.onlyAvailable) {
      params.status = 1; // 假设1代表可用状态
    }
    
    console.log('库位选择器: 请求参数', params);
    
    // 发送请求获取库位列表
    const response = await axios.get('/warehouses/locations', { params });
    
    console.log('库位选择器: 获取库位列表响应', response);
    
    if (response.data && response.data.code === 0 && response.data.data) {
      let locationList = [];
      
      if (Array.isArray(response.data.data)) {
        locationList = response.data.data;
      } else if (response.data.data.list && Array.isArray(response.data.data.list)) {
        locationList = response.data.data.list;
      }
      
      // 应用自定义过滤
      if (props.filterFn && typeof props.filterFn === 'function') {
        locationList = locationList.filter(props.filterFn);
      }
      
      // 转换为选项格式
      locationOptions.value = locationList.map(item => ({
        value: item.id,
        label: `${item.code} ${item.name || ''}`,
        code: item.code,
        name: item.name,
        area: item.area,
        shelf: item.shelf,
        level: item.level,
        status: item.status,
        warehouseId: item.warehouseId,
        capacity: item.capacity,
        currentQuantity: item.currentQuantity
      }));
      
      console.log('库位选择器: 处理后的选项列表', locationOptions.value);
    } else {
      console.warn('库位选择器: 响应格式不符合预期', response.data);
      Message.warning('获取库位数据格式异常');
    }
  } catch (error) {
    console.error('库位选择器: 获取库位列表失败', error);
    Message.error('获取库位列表失败');
    locationOptions.value = [];
  } finally {
    loading.value = false;
  }
};

// 如果提供了默认选中的库位ID但没有找到对应的库位，加载该库位信息
const loadLocationById = async (locationId) => {
  if (!locationId) return;
  
  // 检查是否已经在选项中
  if (locationOptions.value.some(item => item.value === locationId)) {
    return;
  }
  
  console.log('库位选择器: 尝试通过ID加载单个库位', locationId);
  
  try {
    const response = await axios.get(`/warehouses/locations/${locationId}`);
    
    if (response.data && response.data.code === 0 && response.data.data) {
      const location = response.data.data;
      
      // 添加到选项列表
      locationOptions.value.push({
        value: location.id,
        label: `${location.code} ${location.name || ''}`,
        code: location.code,
        name: location.name,
        area: location.area,
        shelf: location.shelf,
        level: location.level,
        status: location.status,
        warehouseId: location.warehouseId,
        capacity: location.capacity
      });
      
      console.log('库位选择器: 单个库位加载成功', location);
    }
  } catch (error) {
    console.error('库位选择器: 加载指定库位失败', error);
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  console.log('[LocationSelector] Component mounted. Fetching initial data...');
  // 根据操作类型获取合适的库位数据
  await fetchLocations(); 
  
  // 如果有初始值，尝试找到并设置它 (需要确保 locations 数据结构包含 id)
  if (props.modelValue && locations.value.length > 0) {
    const initialLocation = locations.value.find(loc => loc.id === props.modelValue);
    if (initialLocation) {
      selectLocation(initialLocation);
    }
  }
});

// 导出方法供父组件使用
defineExpose({
  refreshLocations
});
</script>

<style scoped>
.location-selector {
  margin-bottom: 12px;
}

.selector-content {
  max-width: 1000px;
  margin: 0 auto;
}

.location-search {
  margin-bottom: 10px;
}

.location-filters {
  margin-bottom: 10px;
}

.location-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  margin-top: 10px;
}

.location-cell {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  height: 75px;
  display: flex;
  flex-direction: column;
}

.location-cell:hover {
  border-color: #165dff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
}

.location-cell.selected {
  border-color: #165dff;
  background-color: rgba(22, 93, 255, 0.1);
}

.location-cell.available {
  background-color: rgba(82, 196, 26, 0.05);
}

.location-cell.full {
  background-color: rgba(250, 173, 20, 0.05);
}

.location-cell.locked {
  background-color: rgba(245, 34, 45, 0.05);
  opacity: 0.7;
}

.location-code {
  font-weight: 500;
  margin-bottom: 4px;
}

.location-info {
  margin-top: auto;
}

.location-stock-info {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.65);
}

.location-usage {
  height: 4px;
  background-color: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 4px;
}

.usage-bar {
  height: 100%;
  background-color: #165dff;
}

.location-selected {
  margin-top: 24px;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

.location-action {
  margin-top: 16px;
  text-align: right;
}

.location-quantity-selector {
  margin-top: 16px;
}

.max-quantity {
  margin-left: 8px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
}

:deep(.location-row-selected) {
  background-color: rgba(22, 93, 255, 0.1);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style> 